import { asyncRoutes, constRoutes } from '@/router';


function hasPermission(roles, route, rootState) {
    if (route.meta && route.meta.modulesName) {
        if (route.meta && route.meta.roles) {
            return roles.some(role => route.meta.roles.includes(role)) && rootState.user.modulesName === route.meta.modulesName;
        } else {
            return rootState.user.modulesName === route.meta.modulesName;
        }
    } else {
        if (route.meta && route.meta.roles) {
            return roles.some(role => route.meta.roles.includes(role))
        } else {
            return true;
        }
    }
}

export function filterAsyncRoutes(routes, roles, rootState) {
    const res = [];
    routes.forEach(route => {
        const tmp = {...route };
        if (hasPermission(roles, tmp, rootState)) {
            if (tmp.children) {
                tmp.children = filterAsyncRoutes(tmp.children, roles, rootState);
            }
            res.push(tmp)
        }
    })
    return res;
}


const state = {
    routes: [], //完整路由表
    addRoutes: [], //用户可访问路由表
}
const mutations = {
    SET_ROUTES: (state, routes) => {
        state.addRoutes = routes;
        state.routes = constRoutes.concat(routes);
    }
}

const actions = {
    // 路由生成，在得到用户角色后第一时间调用
    generateRoutes({ commit, rootState }, roles) {
        return new Promise(resolve => {
            // 用户是管理员则拥有完整访问权限
            let accessedRoutes = filterAsyncRoutes(asyncRoutes, roles, rootState)
            commit('SET_ROUTES', accessedRoutes)
            resolve(accessedRoutes)
        })
    }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}